extends Node2D

@onready var net = $net
@onready var fishes_store = $Fishes
@onready var pond = $pond

const Fish = preload("res://scenes/fish/fish.tscn")
const Diseased_Fish = preload("res://scenes/fish/diseased_fish/diseased_fish.tscn")

var radius : int = 200
var center : Vector2 = Vector2(576,324)
var target_point : Vector2 = Vector2(576,44)

var fishes_count : Vector2 = Vector2(2, 1)

var is_queud_respawn : bool = false

var is_initing = false
func _ready() -> void:
	Globals.normal_fish_collected.connect(on_normal_fish_collected)
	Globals.diseased_fish_collected.connect(on_diseased_fish_collected)
	pond.spawn_fishes(fishes_count)

func _draw() -> void:
	draw_circle(target_point, 10, Color.YELLOW)

func _physics_process(delta: float) -> void:
	if not net.is_moving:
		rotate_target_point(delta)
		if Input.is_action_just_pressed("player_action"):
			net.move(target_point)
		if is_queud_respawn:
			pond.clear_fishes()
			fishes_count += Vector2(1, 1)
			pond.spawn_fishes(fishes_count)
			is_queud_respawn = false

func rotate_target_point(delta: float) -> void:
	target_point = center + (target_point - center).rotated(deg_to_rad(90)*delta)
	queue_redraw()

func _on_fishes_child_exiting_tree(fish: Node) -> void:
	#check diseased_fish
	if not is_initing:
		if fish is DiseasedFish:
			is_initing = true
			reload()
			return
		#check end
		var is_playing = false
		for fish_ in fishes_store.get_children():
			if not fish_ is DiseasedFish and fish != fish_:
				is_playing = true
#		if not is_playing:
#			if is_adding_normal:
#				fishes_count.y +=1
#			else:
#				fishes_count.x += 1
#			is_adding_normal = not is_adding_normal
#			is_initing = true
			#clear_fishes()
			#spawn_fishes.call_deferred()
			return

func reload() -> void:
	net.position = Vector2(576,44)
	target_point = Vector2(576,44)
	fishes_count = Vector2(2, 1)
	#is_adding_normal = false
	#clear_fishes()
	#spawn_fishes.call_deferred()

func respawn_fishes() -> void:
	is_initing = true
	#clear_fishes()
	#spawn_fishes.call_deferred()
	set_deferred("is_initing", false)

func on_normal_fish_collected() -> void:
	pond.normal_fish_count -= 1
	if not pond.contains_normal_fish():
		is_queud_respawn = true

func on_diseased_fish_collected() -> void:
	get_tree().reload_current_scene()
